﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameLib.Utils
{
	/// <summary>
	/// Fast string-based identifier
	/// </summary>
	public class Name
	{
		private Name(string nameString)
		{
			m_NameString = nameString;
			Register(this);
		}

		public override int GetHashCode()
		{
			return m_Id;
		}

		public static Name Find(string nameString)
		{
			Name result = null;
			m_Names.TryGetValue(nameString, out result);

			return result;
		}

		public static Name FromString(string nameString)
		{
			var name = Find(nameString);

			if (name != null)
				return name;
			else
				return new Name(nameString);
		}

		private static void Register(Name name)
		{
			if (ms_LastUsedIndex == -1)
				throw new Exception("exceed the maximum number of names can be used!");

			if (m_Names.ContainsKey(name.m_NameString))
				throw new Exception(string.Format("Duplicated name {0}", name.m_NameString));

			name.m_Id = ++ms_LastUsedIndex;

			m_Names[name.m_NameString] = name;
		}

		public override string ToString()
		{
			return m_NameString;
		}

		private int m_Id;
		private string m_NameString;
		private static int ms_LastUsedIndex = 0;
		private static Dictionary<string, Name> m_Names = new Dictionary<string, Name>();

	}
}
